const { app } = require('electron')
const fs = require('fs');
const path = require('path');
const logPath = './logs'
const maxCatchHours = 24 * 30; // 日志最大保留时间（小时）

/**
 * 异步递归获取目录下所有文件路径
 * @param {string} dir - 目标目录路径
 * @param {boolean} includeChild - 是否需要搜寻子文件夹
 * @returns {Promise<string[]>} 所有文件的绝对路径数组
 */
async function getAllFilesRecursive(dir, includeChild) {
    let allFiles = [];
    try {
        const entries = fs.readdirSync(dir, { withFileTypes: true });
        if (entries) {
            for (const entry of entries) {
                const entryPath = path.join(dir, entry.name);
                if (includeChild && entry.isDirectory()) {
                    const subDirFiles = await getAllFilesRecursive(entryPath);
                    allFiles = [...allFiles, ...subDirFiles];
                } else if (entry.isFile()) {
                    allFiles.push(entryPath);
                }
            }
        }
    } catch (err) {
      throw err
    }
    return allFiles;
}
/**
 * 获取当前日期
 * @returns 
 */
function getTime(){
    return [new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()].join('-');
}
/**
 * 参数转换为字符串
 * @param {*} args 
 * @returns {string}
 */
function getContent(args){
    let str = ''
    args.forEach(item => {
        str += " | "
        if(item && typeof item === 'object') {
            str += JSON.stringify(item)
        } else if (item === null) {
            str += 'null'
        } else if (item === undefined) {
            str += 'undefined'
        } else {
            str += item
        }
    });
    return str
}

/**
 * 文件写入
 * @param {*} filename 文件名
 * @param {*} content 内容
 */
function fileWrite(filename, content){
    const root = path.join(__dirname, logPath)
    if(!fs.existsSync(root)){
        fs.mkdirSync(root)
    }
    const logFilePath = path.join(__dirname, filename)
    if (!fs.existsSync(logFilePath)) fs.writeFileSync(logFilePath, '');
    const data = new Date().toLocaleString() + " " + content + '\n';
    fs.appendFile(logFilePath, data, () => {});
}

/**
 * 清理过期日志
 */
async function clearHistoryLogs(){
    const filepath = await getAllFilesRecursive(path.join(__dirname, logPath), false)
    filepath.forEach(path => {
        if(/(console|app)/.test(path)) {
            const fileTime = path.match(/[0-9]+-[0-9]+-[0-9]+/)?.[0]
            if(new Date().getTime() - maxCatchHours * 60 * 60 * 1000 > new Date(fileTime).getTime()) {
                fs.unlink(path, () => {})
            }
        }
    })
}

/**
 * 保存网页控制台日志
 * @param  {...any} arg 
 */
function saveConsoleLog(...arg) {
    const content = getContent(arg)
    const filename = `${logPath}/console-${ getTime() }.log`
    fileWrite(filename, content)
}

/**
 * 保存壳子常规日志
 * @param  {...any} arg 
 */
function saveAPPLog(...arg) {
    const content = getContent(arg)
    const filename = `${logPath}/app-${ getTime() }.log`
    fileWrite(filename, content)
}

/**
 * 保存壳子错误日志
 * @param  {...any} arg 
 */
function saveErrorLog(...arg) {
    const content = getContent(arg)
    const filename = `${logPath}/error-${ getTime() }.log`
    fileWrite(filename, content)
}

module.exports = {
    saveConsoleLog,
    saveAPPLog,
    saveErrorLog,
    clearHistoryLogs,
};